import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {AlertComponent, AlertOptions, getProperty, MessageService, ModalComponent, paginationFactory, PaginationService, ServerConfigService, Table} from '../../../../../ng-tools';
import {TicketService} from '../../../../services/api/ticket.service';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Router} from '@angular/router';
import {RobotEditComponent} from '../robot-edit/robot-edit.component';
import {AccountDetailComponent} from '../account-detail/account-detail.component';

const paginationProvider = {
  provide: PaginationService,
  useFactory: paginationFactory,
  deps: [HttpClient, TicketService]
};

@Component({
  selector: 'user-manager',
  templateUrl: './user-manager.component.html',
  styleUrls: ['./user-manager.component.scss'],
  providers: [paginationProvider]
})
export class UserManagerComponent implements OnInit, AfterViewInit {
  breadcrumb = [
    {name: '用户管理', cssIcon: 'fa fa-fw fa-user-circle-o'}
  ];
  @ViewChild('modal') modal: ModalComponent;
  @ViewChild('alert') alert: AlertComponent;
  alertOptions: AlertOptions = {
    theme: 'danger',
    data: null,
    position: 'center'
  };
  agentData;
  resetPasswordData;
  freezeData;
  cancleAgentData;
  currentRowIndex;
  page = 1;
  selectInfo = {
    search: {
      title: '搜索',
      name: 'searchKey',
      placeholder: '请输入关键字'
    }
  };
  userTable = new Table({
    headers: [
      {propName: 'username', displayName: '登录用户名'},
      {propName: 'nickName', displayName: '用户昵称'},
      {propName: 'userUid', displayName: '用户ID'},
      {propName: 'inviteCode', displayName: '邀请码'},
      {propName: 'account', displayName: '账户余额'},
    ],
  });
  buttons = [];
  freezeType;
  constructor(private message: MessageService,
              private router: Router,
              public pagination: PaginationService,
              private serviceConfig: ServerConfigService,
              private ticketService: TicketService) {
  }

  ngOnInit() {

    this.getInfo(1, undefined);
  }

  get getProperty() {
    return getProperty;
  }

  getInfo(page, searchKey) {
    this.buttons = [];
    this.pagination.simpleFormatter = this.userTable.options.headers;
    let queryParams;
    if (searchKey === undefined) {
      queryParams = new HttpParams().append('web_token', localStorage.getItem('token'))
        .append('pageNum', page + '')
        .append('pageSize', '10');
    } else {
      queryParams = new HttpParams().append('web_token', localStorage.getItem('token'))
        .append('pageNum', page + '')
        .append('pageSize', '10')
        .append('searchKey', searchKey);
    }
    this.ticketService.get(this.ticketService.urls.getUsers, {
      observe: 'response',
      params: queryParams
    }).subscribe((resp) => {
      if (resp.body.success) {
        const result = resp.body.returnValue.page;
        this.pagination.page.results = result.list;
        this.pagination.page.totalPage = result.pages;
        this.pagination.page.pageNumber = result.pageNum;
        this.pagination.page.pageSize = result.pageSize;
        this.pagination.formatData();
        this.pagination.dataLoadSubscriber$.subscribe(() => {
          for (const item of this.pagination.page.results) {
            let buttonItem = [];
            if (item.isCustom === false) {
              if (item.isAgent === 0) {
                buttonItem = [{
                  btnClass: 'btn btn-link p-0',
                  text: '账户明细',
                  isShow: true,
                  click: (e) => {
                    this.showAccountDetail(e);
                  }
                },
                  {
                    btnClass: 'btn btn-link p-0',
                    text: '重置密码',
                    isShow: true,
                    click: (e) => {
                      this.showResetPasswordModal(e);
                    }
                  }
                ];
              }
              if (item.isAgent === 1) {
                buttonItem = [
                  {
                    btnClass: 'btn btn-link p-0',
                    text: '账户明细',
                    isShow: true,
                    click: (e) => {
                      this.showAccountDetail(e);
                    }
                  },
                  {
                    btnClass: 'btn btn-link p-0',
                    text: '重置密码',
                    isShow: true,
                    click: (e) => {
                      this.showResetPasswordModal(e);
                    }
                  },
                ];
              }
              if (item.userStatus === 1) {
                buttonItem.push({
                  btnClass: 'btn-danger p-0',
                  text: '冻结账号',
                  isShow: true,
                  click: (e) => {
                    this.showFreezeAccount(e);
                    this.freezeType = 0;
                  }
                });
              }
              if (item.userStatus === 0) {
                buttonItem.push({
                  btnClass: 'btn-success p-0',
                  text: '解冻账号',
                  isShow: true,
                  click: (e) => {
                    this.showFreezeAccount(e);
                    this.freezeType = 1;
                  }
                });
              }
            }
            this.buttons.push(buttonItem);
          }
          this.message.sendMessage('page load progress', this);
        });
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }
  showAccountDetail(e) {
    this.ticketService.get(this.ticketService.urls.getUserOrderInfo, {
      observe: 'response',
      params: new HttpParams()
          .append('web_token', localStorage.getItem('token'))
          .append('userId', e.userUid)
          .append('pageNum', 1 + '')
          .append('pageSize', '10')}).subscribe((resp) => {
      if (resp.body.success) {
        if (resp.body.returnValue.page.total > 0) {
          this.modal.show({
            title: '账单明细',
            cssIcon: 'fa fa-fw fa-info-circle',
            dynamicComponent: {
              component: AccountDetailComponent,
              data: e,
              events: {
                success: (data) => {
                  this.modal.hide();
                }
              },
            },
            data: null
          });
        } else {
          const options = {
            id: 'resetPassword',
            title: '提示',
            cssIcon: 'fa fa-fw fa-warning',
            size: 'sm',
            theme: 'danger',
            backdrop: 'static',
            data: '该用户暂无数据',
            closeBtn: true,
          };
          this.modal.show(options);
        }
      } else {
        this.router.navigateByUrl('/login').catch();
      }
    });
  }

  showResetPasswordModal(e) {
    const options = {
      id: 'resetPassword',
      title: '重置密码',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否重置此用户的密码？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.resetPasswordData = e;
  }

  showFreezeAccount(e) {
    const options = {
      id: 'freezeAccount',
      title: '冻结账户',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否冻结此账户？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.freezeData = e;
  }

  showCanceAgentlModal(e) {
    const options = {
      id: 'cancelAgent',
      title: '代理设置',
      cssIcon: 'fa fa-fw fa-warning',
      size: 'sm',
      theme: 'danger',
      backdrop: 'static',
      data: '是否取消此用户的代理权限？',
      closeBtn: true,
      confirmBtn: true
    };
    this.modal.show(options);
    this.cancleAgentData = e;
  }

  firstPage() {
    this.buttons = [];
    this.page = 1;
    this.getInfo(1, undefined);
  }

  previousPage() {
    this.buttons = [];
    if (this.page > 1) {
      this.page = this.page - 1;
    } else {
      this.page = 1;
    }
    this.getInfo(this.page, undefined);
  }

  nextPage() {
    this.buttons = [];
    if (this.page < this.pagination.page.totalPage) {
      this.page = this.page + 1;
    } else {
      this.page = this.pagination.page.totalPage;
    }
    this.getInfo(this.page, undefined);
  }

  lastPage() {
    this.buttons = [];
    this.page = this.pagination.page.totalPage;
    this.getInfo(this.pagination.page.totalPage, undefined);
  }

  btnClicked(e, btnIndex, rowIndex) {
    this.currentRowIndex = rowIndex;
    const data = this.pagination.page.results[rowIndex];
    const func = this.buttons[rowIndex][btnIndex].click;
    e.stopPropagation();
    if (typeof func === 'function') {
      this.buttons[rowIndex][btnIndex].click(data, rowIndex);
    }
  }

  eventHandler() {
    this.modal.event.subscribe({
      next: (event) => {
        if (event.name === 'confirm' && event.id === 'setAgent') {
          this.modal.hide();
          this.setAgent();
        }
        if (event.name === 'confirm' && event.id === 'cancelAgent') {
          this.modal.hide();
          this.cancelAgent();
        }
        if (event.name === 'confirm' && event.id === 'resetPassword') {
          this.modal.hide();
          this.resetPassword();
        }
        if (event.name === 'confirm' && event.id === 'freezeAccount') {
          this.modal.hide();
          this.freezeAccount(this.freezeType);
        }
      }
    });
  }
  selectUser(event) {
    this.getInfo(1, event.normal.searchKey);
  }
  freezeAccount(freeze) {
    this.ticketService.post(this.ticketService.urls.freezeUser, {'userId': this.freezeData.userUid, 'status': freeze}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))
    }).subscribe((resp) => {
      if (resp.body.success) {
        this.buttons = [];
        this.getInfo(this.page, undefined);
      } else {
        this.alertOptions.data = resp.body.msg;
        this.alert.show(this.alertOptions, 2000);
      }
    });
  }

  resetPassword() {
    this.ticketService.post(this.ticketService.urls.resetPwd, {'userId': this.resetPasswordData.userUid}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))
    }).subscribe((resp) => {
      if (resp.body.success) {
        this.buttons = [];
        this.getInfo(this.page, undefined);
      } else {
        this.alertOptions.data = resp.body.msg;
        this.alert.show(this.alertOptions, 2000);
      }
    });
  }

  setAgent() {
    this.ticketService.post(this.ticketService.urls.etOrCancelAgent, {'userId': this.agentData.userUid, 'isAgent': 1}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))
    }).subscribe((resp) => {
      if (resp.body.success) {
        this.buttons = [];
        this.getInfo(this.page, undefined);
      } else {
        this.alertOptions.data = resp.body.msg;
        this.alert.show(this.alertOptions, 2000);
      }
    });
  }

  cancelAgent() {
    this.ticketService.post(this.ticketService.urls.etOrCancelAgent, {'userId': this.cancleAgentData.userUid, 'isAgent': 0}, {
      observe: 'response',
      params: new HttpParams().append('web_token', localStorage.getItem('token'))
    }).subscribe((resp) => {
      if (resp.body.success) {
        this.buttons = [];
        this.getInfo(this.page, undefined);
      } else {
        this.alertOptions.data = resp.body.msg;
        this.alert.show(this.alertOptions, 2000);
      }
    });
  }

  ngAfterViewInit(): void {
    this.eventHandler();
    this.message.sendMessage('breadcrumb changed', this, this.breadcrumb);
    this.message.sendMessage('page load progress', this, '300ms');
  }
}
